package com.cyh.structurealgorithm;

import java.util.Arrays;

public class RadixSort {
    public static void test() {
        //int arr[] = {3, 9, -1, 10, -2, 5, 10, 3, 11, -8, -2};
        int arr[] = {3, 9, 1, 10, 2, 5, 10, 3, 11, 8, 2};
        int[][] bucket = new int[10][arr.length];//10个桶
        int[] bucketElementCounts = new int[10]; //记录每个桶放了多少个数据
        //找到数组中最大的位数
        int max = arr[0];
        for(int i = 1; i < arr.length; i++) {
            if(arr[i] > max) {
                max = arr[i];
            }
        }
        int maxLength = (max + "").length();

        for(int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            //第一轮个位数，第二轮十位数，以此类推，放入对应的桶中
            for(int j = 0; j < arr.length; j++) {
                //取出对应位数的值
                int digitOfElement = arr[j] / n % 10;
                //放入对应的桶中
                bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
                bucketElementCounts[digitOfElement]++;
            }

            //按照桶的顺序取数据，放到原数组中
            int index = 0;
            for(int k = 0; k < bucketElementCounts.length; k++) {
                //如果桶数据不为空
                if(bucketElementCounts[k] != 0) {
                    for(int l = 0; l < bucketElementCounts[k]; l++) {
                        arr[index++] = bucket[k][l];
                    }
                }
                bucketElementCounts[k] = 0;
            }
        }

        System.out.println(Arrays.toString(arr));
    }
}
